package repository

import (
	"context"
	"go-pan/internal/model"

	"gorm.io/gorm"
)

type FileChunkRepository interface {
	// 创建分片记录
	Create(ctx context.Context, chunk *model.FileChunk) error

	// 批量创建分片
	BatchCreate(ctx context.Context, chunks []*model.FileChunk) error

	// 查询文件的所有分片（按 chunk_index 排序）
	GetByFileID(ctx context.Context, fileID int64) ([]*model.FileChunk, error)

	// 删除文件的所有分片
	DeleteByFileID(ctx context.Context, fileID int64) error

	// 根据 MD5 查找分片（用于去重）
	FindByMD5(ctx context.Context, chunkMD5 string) (*model.FileChunk, error)
}

type fileChunkRepository struct {
	db *gorm.DB
}

func NewFileChunkRepository(db *gorm.DB) FileChunkRepository {
	return &fileChunkRepository{db: db}
}

func (r *fileChunkRepository) Create(ctx context.Context, chunk *model.FileChunk) error {
	return r.db.WithContext(ctx).Create(chunk).Error
}

func (r *fileChunkRepository) BatchCreate(ctx context.Context, chunks []*model.FileChunk) error {
	return r.db.WithContext(ctx).Create(&chunks).Error
}

func (r *fileChunkRepository) GetByFileID(ctx context.Context, fileID int64) ([]*model.FileChunk, error) {
	var chunks []*model.FileChunk
	if err := r.db.WithContext(ctx).
		Where("file_id = ?", fileID).
		Order("chunk_index ASC").
		Find(&chunks).Error; err != nil {
		return nil, err
	}
	return chunks, nil
}

func (r *fileChunkRepository) DeleteByFileID(ctx context.Context, fileID int64) error {
	return r.db.WithContext(ctx).
		Where("file_id = ?", fileID).
		Delete(&model.FileChunk{}).Error
}

func (r *fileChunkRepository) FindByMD5(ctx context.Context, chunkMD5 string) (*model.FileChunk, error) {
	var chunk model.FileChunk
	if err := r.db.WithContext(ctx).
		Where("chunk_md5 = ?", chunkMD5).
		First(&chunk).Error; err != nil {
		return nil, err
	}
	return &chunk, nil
}
